package nettyTest.netty3Test.https.https2;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslHandler;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * @author      : yang.xp
 * @date        : 2021/8/19 15:04
 * @description : https://blog.csdn.net/Site_Dave/article/details/90699459
 * keytool -genkey -alias test -keypass 555555 -keyalg RSA -sigalg sha256withrsa -keysize 1024 -validity 365 -keystore d:/test.jks -storepass 555555
 * ————————————————
 * 版权声明：本文为CSDN博主「ZKNA_」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
 * 原文链接：https://blog.csdn.net/Site_Dave/article/details/90699459
 */
public class HttpsServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline ph = ch.pipeline();
        //添加sslhandler
        char[] passArray = "555555".toCharArray(); //jks密码
        SSLContext sslContext = SSLContext.getInstance("TLSv1");
        KeyStore ks = KeyStore.getInstance("JKS");
        //加载keytool 生成的文件
        FileInputStream inputStream = new FileInputStream("d:/test.jks");
        ks.load(inputStream, passArray);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, passArray);
        sslContext.init(kmf.getKeyManagers(), null, null);
        inputStream.close();
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        ch.pipeline().addLast(new SslHandler(sslEngine));
        //处理http服务的关键handler
        //一个组合的HttpRequestDecoder和HttpResponseEncoder使得服务器端HTTP实现更容易。
        ph.addLast("codec", new HttpServerCodec());
        ph.addLast("aggregator", new HttpObjectAggregator(10 * 1024 * 1024));
        ph.addLast("handler", new HttpServerHandler());// 服务端逻辑处理类
    }
}
